/*
 * Copyright (c) 2024 iSOFT INFRASTRUCTURE SOFTWARE CO., LTD.
 * easyAda is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */

#ifndef MUTEX_H
#define MUTEX_H

#include <core/object.h>
#include <core/task.h>
#include <core/schedule.h>

#include <stdlib/stdint.h>
#include <tools/list.h>

typedef struct mutex {
    atomic_t lock;
    list_t   wait_list;
    tcb_t   *owner;
    list_t   ownerlist;
    int      maxsem;
    unsigned char maxprior;
    object_t obj;
} DEFAULT_ALINMENT mutex_t;

static inline void try_promote(tcb_t *tcb, int newprior)
{
    mutex_t *target_m;
    if (tcb->priority == newprior) {
        return;
    }
    schedule_try_changeprior(tcb, newprior);
    if (!tcb->lock) {
        return;
    }
    switch(tcb->locktype) {
        case CAP_MUTEX:
            target_m = tcb->lock;
            if (target_m->maxprior <= newprior) {
                return;
            }
            target_m->maxprior = newprior;
            try_promote(target_m->owner, newprior);
	    break;
        default:
            break;
    }
}

static inline void mutex_get(mutex_t *mutex)
{
    object_get(&mutex->obj);
}

static inline void mutex_put(mutex_t *mutex)
{
    object_put(&mutex->obj, offset_of(mutex_t, obj), sizeof(mutex_t));
}

void          mutex_init(mutex_t *mutex, int sema);
void          mutex_lock(mutex_t *mutex);
void          mutex_unlock(mutex_t *mutex);
int           mutex_trylock(mutex_t *mutex);
cptr_t        mutex_owner(mutex_t *mutex);
unsigned long mutex_destroy(capability_t *cap, mutex_t *mutex);

#endif
